<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-10-13 16:00:11
 * @version $Id$
 */
namespace payinterface;

require('Utils.class.php');

require_once "class/ClientResponseHandler.class.php";
require_once 'class/PayHttpClient.class.php' ;
require_once 'class/RequestHandler.class.php' ;

class PaySdk {
    
    private $resHandler = null;
    private $reqHandler = null;
    private $pay = null;

    function __construct($opt){
    	$this->conf = $opt;

        $this->Request();
    }

    public function Request(){
        $this->resHandler = new \ClientResponseHandler();
        $this->reqHandler = new \RequestHandler();
        $this->pay = new \PayHttpClient();

        $this->reqHandler->setGateUrl($this->conf['url']);
        $this->reqHandler->setKey($this->conf['key']);
    }

    /**
     * 提交订单信息
     */
    public function submitOrderInfo($opt){

        $this->reqHandler->setReqParams($opt,array('method'));
        $this->reqHandler->setParameter('service',$this->conf['service']?:'pay.weixin.jspay');//接口类型
        $this->reqHandler->setParameter('mch_id',$this->conf['mchId']);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('version',$this->conf['version']);
        // $this->reqHandler->setParameter('limit_credit_pay','1');
		// $this->reqHandler->setParameter('op_user_id','yida');
		//$this->reqHandler->setParameter('appid','wx50bb165fb00ef149');
		// $this->reqHandler->setParameter('op_shop_id','yida1');
		// $this->reqHandler->setParameter('op_device_id','yida2');
		// $this->reqHandler->setParameter('device_info','yida3');
		//$this->reqHandler->setParameter('time_expire','20170306152200');
		// $this->reqHandler->setParameter('is_raw','1');
        //通知地址，必填项，接收平台通知的URL，需给绝对路径，255字符内格式如:http://wap.tenpay.com/tenpay.asp
        //$notify_url = 'http://'.$_SERVER['HTTP_HOST'];
        //$this->reqHandler->setParameter('notify_url',$notify_url.'/payInterface/request.php?method=callback');
		$this->reqHandler->setParameter('notify_url',$this->conf['notify_url']);//
		$this->reqHandler->setParameter('callback_url',isset($opt['callback_url'])?$opt['callback_url']:$this->conf['callback_url']);
        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
		//$this->reqHandler->setParameter('sub_openid','oZ1CSjktOzQRa-q2feBrBXg9VXuM');
        $this->reqHandler->createSign();//创建签名
        
        $data = Utils::toXml($this->reqHandler->getAllParameters());
        
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            if($this->resHandler->isTenpaySign()){
                //当返回状态与业务结果都为0时才返回，其它结果请查看接口文档
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    return array('status'=>1,'msg'=>'SUCCESS','data'=>array('token_id'=>$this->resHandler->getParameter('token_id'),'pay_info'=>$this->resHandler->getParameter('pay_info')));
                }else{
                    return array('status'=>0,'msg'=>'Error Code1:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message'));
                }
            }
            return array('status'=>0,'msg'=>'Error Code2:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message'));
        }else{
            return array('status'=>0,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo());
        }
    }

    /**
     * 查询订单
     */
    public function queryOrder($opt){
        $this->reqHandler->setReqParams($opt,array('method'));
        $reqParam = $this->reqHandler->getAllParameters();
        if(empty($reqParam['transaction_id']) && empty($reqParam['out_trade_no'])){
            return array('status'=>0, 'msg'=>'请输入商户订单号或平台订单号!');
        }
        // $this->reqHandler->setParameter('version',$this->conf['version']);
        $this->reqHandler->setParameter('service','unified.trade.query');//接口类型
        $this->reqHandler->setParameter('mch_id',$this->conf['mchId']);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());

        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            if($this->resHandler->isTenpaySign()){
                $res = $this->resHandler->getAllParameters();
                return array('status'=>1,'msg'=>'SUCCESS','data'=>$res);
            }
            echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message')));
            return array('status'=>0,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message'));
        }else{
            echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
            return array('status'=>0,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo());
        }
    }

	/**
     * 提交退款
     */
    public function submitRefund($opt){
        $this->reqHandler->setReqParams($opt,array('method'));
        $reqParam = $this->reqHandler->getAllParameters();
        if(empty($reqParam['transaction_id']) && empty($reqParam['out_trade_no'])){
            return array('status'=>0, 'msg'=>'请输入商户订单号或平台订单号!');
        }
        // $this->reqHandler->setParameter('version',$this->conf['version']);
        $this->reqHandler->setParameter('service','unified.trade.refund');//接口类型
        $this->reqHandler->setParameter('mch_id',$this->conf['mchId']);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
        $this->reqHandler->setParameter('op_user_id',$this->conf['mchId']);//必填项，操作员帐号,默认为商户号

        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());//将提交参数转为xml，目前接口参数也只支持XML方式

        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            if($this->resHandler->isTenpaySign()){
                //当返回状态与业务结果都为0时才返，其它结果请查看接口文档
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    /*$res = array('transaction_id'=>$this->resHandler->getParameter('transaction_id'),
                                 'out_trade_no'=>$this->resHandler->getParameter('out_trade_no'),
                                 'out_refund_no'=>$this->resHandler->getParameter('out_refund_no'),
                                 'refund_id'=>$this->resHandler->getParameter('refund_id'),
                                 'refund_channel'=>$this->resHandler->getParameter('refund_channel'),
                                 'refund_fee'=>$this->resHandler->getParameter('refund_fee'),
                                 'coupon_refund_fee'=>$this->resHandler->getParameter('coupon_refund_fee'));*/
                    $res = $this->resHandler->getAllParameters();
                    // Utils::dataRecodes('提交退款',$res);
                    // echo json_encode(array('status'=>200,'msg'=>'退款成功,请查看result.txt文件！','data'=>$res));
                    // exit();
                    return array('status'=>1,'msg'=>'SUCCESS','data'=>$res);
                }else{
                    // echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('err_code').' Error Message:'.$this->resHandler->getParameter('err_msg')));
                    // exit();
                    return array('status'=>0,'msg'=>'Error Code:'.$this->resHandler->getParameter('err_code').' Error Message:'.$this->resHandler->getParameter('err_msg'));
                }
            }
            // echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message')));
            return array('status'=>0,'msg'=>'Error Code:'.$this->resHandler->getParameter('status').' Error Message:'.$this->resHandler->getParameter('message'));
        }else{
            // echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
            return array('status'=>0,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo());
        }
    }

    /**
     * 查询退款
     */
    public function queryRefund($opt){
        $this->reqHandler->setReqParams($opt,array('method'));
        if(count($this->reqHandler->getAllParameters()) === 0){
            // echo json_encode(array('status'=>500,
            //                        'msg'=>'请输入商户订单号,平台订单号,商户退款单号,平台退款单号!'));
            // exit();
            return array('status'=>0,'msg'=>'请输入商户订单号,平台订单号,商户退款单号,平台退款单号!');
        }
        $this->reqHandler->setParameter('version',$this->conf['version']);
        $this->reqHandler->setParameter('service','unified.trade.refundquery');//接口类型
        $this->reqHandler->setParameter('mch_id',$this->conf['mchId']);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('nonce_str',mt_rand(time(),time()+rand()));//随机字符串，必填项，不长于 32 位
        
        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());//将提交参数转为xml，目前接口参数也只支持XML方式

        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);//设置请求地址与请求参数
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            if($this->resHandler->isTenpaySign()){
                //当返回状态与业务结果都为0时才返回，其它结果请查看接口文档
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    /*$res = array('transaction_id'=>$this->resHandler->getParameter('transaction_id'),
                                  'out_trade_no'=>$this->resHandler->getParameter('out_trade_no'),
                                  'refund_count'=>$this->resHandler->getParameter('refund_count'));
                    for($i=0; $i<$res['refund_count']; $i++){
                        $res['out_refund_no_'.$i] = $this->resHandler->getParameter('out_refund_no_'.$i);
                        $res['refund_id_'.$i] = $this->resHandler->getParameter('refund_id_'.$i);
                        $res['refund_channel_'.$i] = $this->resHandler->getParameter('refund_channel_'.$i);
                        $res['refund_fee_'.$i] = $this->resHandler->getParameter('refund_fee_'.$i);
                        $res['coupon_refund_fee_'.$i] = $this->resHandler->getParameter('coupon_refund_fee_'.$i);
                        $res['refund_status_'.$i] = $this->resHandler->getParameter('refund_status_'.$i);
                    }*/
                    $res = $this->resHandler->getAllParameters();
                    // Utils::dataRecodes('查询退款',$res);
                    // echo json_encode(array('status'=>200,'msg'=>'查询成功,请查看result.txt文件！','data'=>$res));
                    // exit();
                    return array('status'=>1,'msg'=>'SUCCESS','data'=>$res);
                }else{
                    // echo json_encode(array('status'=>500,'msg'=>'Error Code:'.$this->resHandler->getParameter('message')));
                    // exit();
                    return array('status'=>0,'msg'=>'Error Code:'.$this->resHandler->getParameter('message'));
                }
            }
            // echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getContent()));
            return array('status'=>0,'msg'=>$this->resHandler->getContent());
        }else{
            // echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
            return array('status'=>0,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo());
        }
    }
    
    /**
     * 后台异步回调通知
     */
    public function notify($callback){
        $xml = file_get_contents('php://input');
		// file_put_contents('1.txt',$xml);
        $this->resHandler->setContent($xml);
		//var_dump($this->resHandler->setContent($xml));
        $this->resHandler->setKey($this->conf['key']);
        if($this->resHandler->isTenpaySign()){
            if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
				// $tradeno = $this->resHandler->getParameter('out_trade_no');
				// 此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
				//更改订单状态
				
				// Utils::dataRecodes('接口回调收到通知参数',$this->resHandler->getAllParameters());
				// ob_clean();
				// echo 'success';
				// file_put_contents('2.txt',1);
				// exit();
				$res = $this->resHandler->getAllParameters();

				$re = call_user_func_array($callback,array($res));
				ob_clean();
				if ($re) {
					echo 'success';
				}else{
					echo 'fail';
				}
				exit;
            }else{
                echo 'fail';
            }
        }else{
            echo 'fail';
        }
    }
}